<?php
/**
 *  Routing Class
 *	@todo add class & function checkup
 */
class Route {
	
	/* Private Declaration */
	private $_uri = array(),
            $_method = array();
	
	/**
	 * Building a collection of internal URL's to look for
	 * @param type $uri
	 */
	public function add($uri, $method = NULL) {
		$this->_uri[] = '/' . trim($uri, '/');
        
        if($method != NULL) {
            $this->_method[] = $method;
        }
	}
	
	/**
	 * Makes the thing run
	 */
	public function submit() {
		// $_GET['uri'] comes form the .htaccess file
		$uriGetParam = isset($_GET['uri']) ? '/' . $_GET['uri'] : '/';
		
		// we trim the last '/' if there is any and we check that we do not trim the root '/'
		$uriGetParam = (strlen($uriGetParam) >= 2) ? rtrim($uriGetParam, "/") : $uriGetParam;
		
		// making array() from $_GET['uri']
		// with first parameter being the controller
		// and the following are values
		$uriGetParam = explode('/', $uriGetParam);
		foreach($uriGetParam as $param) {
			$params[] = '/' . $param;
		}
		// getting the method
		$method = $params[1];
		// getting the values that are after the method in the URI
		// they go to an array $values with keys - val_1, val_2, val_3...
		$count = 1;
		$values = array();
		for($i = 2; $i < count($params); $i++) {
			$values['val_' . $count] = trim($params[$i], '/');
			$count++;
		}
 
		foreach($this->_uri as $key => $value) {
            if(preg_match("#^$value$#", $params[1])) {
                
                if(is_string($this->_method[$key])) {
					
					// TODO check if we have the desired class
					
                    // if there is a match we load the chosen CLASS
                    $useClass = $this->_method[$key];
                    new $useClass($values);
                } else {
					
					//TODO check if we have the desired function
					
                    // if there is a match we load the chosen FUNCTION and we can, it is optional pass it an
					// array() which contains all the values after the method in the URI /method/val1/val2...
                    call_user_func($this->_method[$key], $values);
                }

            }
		}
	}
  
}